package com.ahdy.mapper;

import com.ahdy.entity.MedicationRecord;
import com.ahdy.entity.MedicationStatisticsDTO;
import org.apache.ibatis.annotations.*;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

// 8. 用药记录Mapper
@Mapper
public interface MedicationRecordMapper {

    @Insert("INSERT INTO medication_records(task_id, user_id, medication_id, planned_time, actual_time, " +
            "dosage_taken, status, delay_minutes, notes, recorded_by, created_at) " +
            "VALUES(#{taskId}, #{userId}, #{medicationId}, #{plannedTime}, #{actualTime}, #{dosageTaken}, " +
            "#{status}, #{delayMinutes}, #{notes}, #{recordedBy}, #{createdAt})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(MedicationRecord record);

    @Update("UPDATE medication_records SET actual_time=#{actualTime}, dosage_taken=#{dosageTaken}, " +
            "status=#{status}, delay_minutes=#{delayMinutes}, notes=#{notes}, recorded_by=#{recordedBy} WHERE id=#{id}")
    int update(MedicationRecord record);

    @Delete("DELETE FROM medication_records WHERE id=#{id}")
    int deleteById(Integer id);

    @Select("SELECT * FROM medication_records WHERE id=#{id}")
    MedicationRecord findById(Integer id);

    @Select("SELECT * FROM medication_records WHERE task_id=#{taskId}")
    MedicationRecord findByTaskId(Integer taskId);

    @Select("SELECT * FROM medication_records WHERE user_id=#{userId} ORDER BY actual_time DESC")
    List<MedicationRecord> findByUserId(Integer userId);

    @Select("SELECT * FROM medication_records WHERE user_id=#{userId} AND DATE(actual_time) BETWEEN #{startDate} AND #{endDate} ORDER BY actual_time DESC")
    List<MedicationRecord> findByUserIdAndDateRange(@Param("userId") Integer userId, @Param("startDate") LocalDate startDate, @Param("endDate") LocalDate endDate);

    @Delete("DELETE FROM medication_records WHERE user_id=#{userId}")
    int deleteByUserId(Integer userId);

    @Delete("DELETE FROM medication_records WHERE task_id=#{taskId}")
    int deleteByTaskId(Integer taskId);

    // 获取用药依从性统计
    List<MedicationStatisticsDTO> getMedicationComplianceStatistics(@Param("userId") Integer userId, @Param("startDate") LocalDate startDate, @Param("endDate") LocalDate endDate);

    // 获取延迟服药统计
    List<Map<String, Object>> getDelayStatistics(@Param("userId") Integer userId, @Param("days") Integer days);

    // 获取用药记录详情（包含药物信息）
    List<Map<String, Object>> findRecordDetailsWithMedication(@Param("userId") Integer userId, @Param("limit") Integer limit);
}
